<template>
  <div v-for="(word, index) in formFields.freeWords" :key="index" class="flex" align="baseline">
    <a-form-item
      :label="`赠词${index + 1}`"
      class="flex-1"
      :name="['freeWords', index, 'name']"
      :rules="{
        required: true,
        validator: checkFreeWords,
        trigger: 'blur'
      }"
    >
      <a-input v-model:value.trim="word.name" placeholder="请输入赠词" />
    </a-form-item>
    <a-form-item
      label="端口"
      v-if="CiBao || CBYXB || BWSD || BWSDYXB"
      class="ml-2 client-type"
      :name="['freeWords', index, 'clientType']"
      :rules="{
        required: true,
        message: '请选择端口'
      }"
    >
      <a-select
        v-model:value="word.clientType"
        placeholder="请选择端口"
        :options="
          props.record.productId === ProductEnum.BWSD || props.record.productId === ProductEnum.BWSDYXB
            ? platformOptionsSimple
            : platformOptions
        "
      />
    </a-form-item>
    <a-form-item class="ml-2">
      <MinusCircleOutlined class="text-red-400" @click="removeWord(index)" />
    </a-form-item>
  </div>
  <a-form-item>
    <a-button type="dashed" :disabled="shouldDisabled" block @click="emit('on-add')">
      <PlusOutlined />
      新增赠词
    </a-button>
  </a-form-item>
</template>

<script lang="ts" setup name="WordGift">
import { computed, ref } from 'vue'
import { toLabelValue } from '@/utils'
import { useVModel } from '@vueuse/core'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { FreeWord } from '@/services/promotion/updateFreeWord'
import { useCategory } from '@/hooks/useCategotry'
import type { Rule } from 'ant-design-vue/es/form'
import validateFreeWord from '@/services/order/validateFreeWord'
import type { Promotion } from '@/core/interfaces/promotion'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { ProductEnum } from '@/core/enums/platform'

interface Props {
  record: Partial<Promotion>
  data: {
    freeWords: FreeWord[]
    wordNum: number
  }
}

interface Emits {
  (e: 'on-add'): void
}

const props = withDefaults(defineProps<Props>(), {
  data: () => ({
    freeWords: [],
    wordNum: 0
  })
})
const formFields = useVModel(props, 'data')
const emit = defineEmits<Emits>()
const platformOptions = toLabelValue(PlatformKeyMap)
const platformOptionsSimple = ref<any>([
  {
    label: 'PC端',
    value: 0
  },
  {
    label: '移动端',
    value: 1
  }
])
const { CiBao, CBYXB, BWSD, BWSDYXB } = useCategory(props.record.productId)
const [, validFreeWord] = validateFreeWord()

const shouldDisabled = computed(() => {
  return props.data.wordNum === 0 || formFields.value.freeWords.length === props.data.wordNum
})

async function checkFreeWords(rule: Rule, name: string) {
  if (name === '') {
    return Promise.reject('请输入赠词')
  }
  //获取当前输入框的index
  const { field } = rule
  const parts = field.split('.')
  const index = parts[1]
  const currentClientType = formFields.value?.freeWords[index]?.clientType

  const [err] = await validFreeWord({
    name,
    orderId: props.record.orderId,
    clientType:
      props.record.productId === ProductEnum.BWSD || props.record.productId === ProductEnum.BWSDYXB
        ? currentClientType
        : props.record.clientType!
  })

  if (err) {
    return Promise.reject(err?.message)
  } else {
    return Promise.resolve()
  }
}

function removeWord(index: number) {
  if (index !== -1) {
    formFields.value.freeWords.splice(index, 1)
  }
}
</script>

<style lang="scss" scoped>
.client-type {
  min-width: 150px;
}
</style>
